package com.gongzhiyun.springboot3test.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.util.StringUtils;

import java.util.Date;

public class JwtUtils {
    private static final String PASSWORD = "com.gongzhiyun.springboot3.jwt.password";
    private static final int EXPIRE_TIME = 1000 * 60 * 60 * 24 * 7;
    private static final String USER_ID = "userId";

    public static String makeUserIdToken(Integer userId) {
        Date date = new Date();
        long expire = date.getTime() + EXPIRE_TIME;
        date.setTime(expire);
        return JWT.create().withExpiresAt(date).withClaim(USER_ID,userId).sign(Algorithm.HMAC256(PASSWORD));
    }

    public static Integer parseUserIdToken(String token){
    if (!StringUtils.hasText(token)){
        return null;
    }
    try{
        return JWT.require(Algorithm.HMAC256(PASSWORD)).build().verify(token).getClaim(USER_ID).asInt();
    } catch (Exception e) {
        return null;
    }
    }
}
